package com.hepinghospital.user.ui.activity.nursing;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.ui.activity.eyecheck.BigImageActivity;
import com.hepinghospital.user.ui.activity.home.DoctorDetailActivity;
import com.hepinghospital.user.ui.activity.userinfo.MyFamilyActivity;
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog;
import com.hepinghospital.user.ui.dialog.DateTimeDialogFragment;
import com.hepinghospital.user.ui.dialog.PayDialog;
import com.hepinghospital.user.ui.dialog.PayTipDialog;
import com.hepinghospital.user.ui.dialog.RulesDialogFragment;
import com.hepinghospital.user.ui.dialog.SchudeleDialogFragment;
import com.hepinghospital.user.ui.dialog.SelectPicModeDialog;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.PermissionsChecker;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.constant.JDConstant;
import com.rest.observer.BaseObserver;
import com.rest.response.BaseResponse;
import com.rest.response.CloudResponse;
import com.rest.response.Doctor;
import com.rest.response.MyFamilyListResponse;
import com.rest.response.NurseListResponse;

import com.rest.response.Photo;
import com.rest.response.PicUploadResponse;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UriUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2022/8/9 13:34
 */
public class AppointNursePayActivity extends BaseActivity {
    public static final int REQUEST_OPEN_CAMERA = 0x011;
    public static final int REQUEST_GALLERY = 0x022;

    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.tv_level)
    TextView tv_level;
    @BindView(R.id.tv_price)
    TextView tv_price;
    @BindView(R.id.tv_patient_name)
    TextView tv_patient_name;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.edt_state)
    EditText edt_state;
    @BindView(R.id.edt_past)
    EditText edt_past;
    @BindView(R.id.edt_allergy)
    EditText edt_allergy;
    @BindView(R.id.patient_name_container)
    RelativeLayout patient_name_container;
    @BindView(R.id.tv_consult_count)
    TextView tvConsultCount;
    @BindView(R.id.tv_skill)
    TextView tv_skill;
    @BindView(R.id.tv_star)
    TextView tv_star;
    @BindView(R.id.ratingBar)
    RatingBar ratingBar;
    @BindView(R.id.img_head)
    ImageView img_head;
    @BindView(R.id.checkbox)
    CheckBox check;
    @BindView(R.id.tv_detail_one_title)
    TextView tvDetailOneTitle;
    @BindView(R.id.tv_remain_time_title)
    TextView tvRemainTimeTitle;
    @BindView(R.id.tv_detail_two_title)
    TextView tvDetailTwoTitle;
    @BindView(R.id.pay_title)
    RelativeLayout payTitle;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.title)
    RelativeLayout title;
    @BindView(R.id.experience_container)
    LinearLayout experienceContainer;
    @BindView(R.id.tv_agree)
    TextView tvAgree;
    @BindView(R.id.btn_confirm)
    TextView btnConfirm;
    @BindView(R.id.rl_pay_photo)
    RelativeLayout rlPayPhoto;
    @BindView(R.id.btn_yes)
    RadioButton btn_yes;
    @BindView(R.id.btn_no)
    RadioButton btn_no;
    @BindView(R.id.btn_more)
    TextView btnMore;
    @BindView(R.id.tv_doctor_detail)
    TextView tvDoctorDetail;
    @BindView(R.id.info1)
    LinearLayout info1;
    @BindView(R.id.info2)
    LinearLayout info2;
    @BindView(R.id.nested_scrollView)
    NestedScrollView nestedScrollView;

    private MyFamilyListResponse myFamily;
    private DateTimeDialogFragment mDateTimeDialogFragment = null;
    private SchudeleDialogFragment mSchudeleDialogFragment = null;
    private PayDialog mPayDialog;

    NursePayAdapter adapter;
    NurseListResponse.RecordsBean recordsBean;
    Doctor.Schedule schedule;
    String scheduleId, orderId, checkDetailId = "";
    private StringBuilder resourceId = new StringBuilder();
    CloudResponse cloud;
    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri;
    public ProgressDialog dialog;
    IWXAPI api;
    List<Photo> list = new ArrayList<>();
    int type;// 0  图文  1  云  2 云订单 3 药 4 聊天 5 图文订单
    private RulesDialogFragment mRulesDialogFragment;
    private CountDownTimer timer;
    private SelectPicModeDialog mSelectPicModeDialog = null;
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    @SuppressLint("SetTextI18n")
    @Override
    protected void initViews() {
        GridLayoutManager manager = new GridLayoutManager(this, 3);
        recyclerView.setLayoutManager(manager);
        adapter = new NursePayAdapter();
        recyclerView.setNestedScrollingEnabled(false);
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.onDraw(c, parent, state);
            }

            @Override
            public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 1;
            }
        });
        list.add(new Photo());

        btn_yes.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                edt_allergy.setVisibility(View.VISIBLE);
            } else {
                edt_allergy.setVisibility(View.GONE);
            }
        });
        mPermissionsChecker = new PermissionsChecker(mContext);
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void initData() {
        recordsBean = (NurseListResponse.RecordsBean)getIntent().getSerializableExtra(UIConstants.APPOINT_NURSE_PAY_PARAMS);

        tv_name.setText(recordsBean.getName());
        tv_level.setText(recordsBean.getDeptName() + " " + recordsBean.getJobTitle());
        tv_skill.setText(recordsBean.getIntroduction());
        tvConsultCount.setText("咨询数："+recordsBean.getConsultCount());
        tv_star.setText(TextUtils.isEmpty(recordsBean.getScore())?"0.0":recordsBean.getScore());
        ratingBar.setRating(Float.parseFloat(TextUtils.isEmpty(recordsBean.getScore())?"0.0":recordsBean.getScore()));
        ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, recordsBean.getDoctorPicture(), img_head);
  
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_appoint_nurse_pay;
    }


    @OnClick(R.id.btn_confirm)
    void btn_confirm() {

        if (TextUtils.isEmpty(tv_patient_name.getText().toString())) {
            ToastUtil.showToast(mContext, "请先选择就诊人");
            return;
        }
        if (edt_state.getText().toString().length() == 0 || (edt_allergy.getText().toString().length() == 0) && btn_yes.isChecked()) {
            ToastUtil.showToast(mContext, "请填写主诉及过敏史");
            return;
        }
        if (!check.isChecked()) {
            ToastUtil.showToast(mContext, "请选择知情同意书及平台免责声明");
            return;
        }
        if (edt_state.getText().toString().length() < 20) {
            showPayTipDialog();
            return;
        }

        createAppointNurseOrder();

    }

    private void createAppointNurseOrder() {
        if (myFamily == null || TextUtils.isEmpty(myFamily.getPatientId())){
            return;
        }
        RestProxy.getInstance().createAppointNurseOrder(
                myFamily.getPatientId(),
                recordsBean.getDoctorId(),
                edt_state.getText().toString(),
                btn_yes.isChecked()?"1":"0",
                edt_allergy.getText().toString(),
                edt_past.getText().toString(),
                recordsBean.getTbUserId(),
                resourceId.toString(),
                new Observer<BaseResponse>() {

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                Bundle bundle = new Bundle();
                bundle.putBoolean(UIConstants.JUMP_TO_CONSULT,true);
                startActivity(MyNursingOrderActivity.class, bundle);
                finish();
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.showToast(mContext,e.getMessage());
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * “病情描述”的内容少于20个字
     * 支付前的提示弹框
     */
    private void showPayTipDialog() {
        PayTipDialog dialog = PayTipDialog.newInstance();
        dialog.setmListener(new PayTipDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                createAppointNurseOrder();
            }

            @Override
            public void onCancel() {
                edt_state.requestFocus();
                nestedScrollView.scrollTo(0, edt_state.getTop());
            }
        });
        dialog.show(getSupportFragmentManager(), "PayTipDialog");
    }

    @OnClick(R.id.tv_agree)
    void agree() {
        showRulesDialogFragment();
    }

    @OnClick(R.id.btn_more)
    void btn_more() {
        if (tv_skill.getMaxLines() == 2) {
            btnMore.setText("点击收起>");
            tv_skill.setMaxLines(100);
        } else {
            btnMore.setText("点击展开>");
            tv_skill.setMaxLines(2);
        }
    }



    @OnClick(R.id.patient_name_container)
    void patient_name_container() {
        startActivityForResult(MyFamilyActivity.class, 1);
    }

    @OnClick(R.id.tv_doctor_detail)
    public void onViewClicked() {
        //查看医生详情
        Bundle bundle = new Bundle();
        bundle.putSerializable("id", recordsBean.getDoctorId());
        startActivity(DoctorDetailActivity.class, bundle);
    }

    /**
     * 上传图片
     *
     * @time 2020/12/2 9:43
     */

    class NursePayAdapter extends RecyclerView.Adapter<NursePayAdapter.Holder> {

        public NursePayAdapter() {
        }

        @NotNull
        @Override
        public Holder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new NursePayAdapter.Holder(LayoutInflater.from(mContext).inflate(R.layout.item_photo, parent, false));
        }

        @Override
        public void onBindViewHolder(final Holder holder, final int position) {
            Log.d("__adapter-1","position = "+position + " type = "+type);
            if (position == 0) {
                if (type == 1 || type == 0) {
                    holder.image.setImageResource(R.mipmap.btn_add_photo);
                    holder.btn_del_photo.setVisibility(View.GONE);
                } else {
                    if (!TextUtils.isEmpty(list.get(position).url)) {
                        ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).url, holder.image);
                    } else if (!TextUtils.isEmpty(list.get(position).uri)) {
                        ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).uri, holder.image);
                    }
                }
            } else {
                if (!TextUtils.isEmpty(list.get(position).url)) {
                    ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).url, holder.image);
                } else if (!TextUtils.isEmpty(list.get(position).uri)) {
                    ImageLoaderHelper.getInstance().GlideImageLoader(mContext, list.get(position).uri, holder.image);
                }
                holder.btn_del_photo.setVisibility(View.VISIBLE);
                holder.btn_del_photo.setOnClickListener(v -> {
                    list.remove(position);
                    notifyDataSetChanged();
                });

            }
            holder.image.setOnClickListener(v -> {
                if (type == 1 || type == 0) {
                    if (position == 0) {
                        if (list.size() > 20) {
                            ToastUtil.showToast(mContext, "上传图片数量已达20张");
                            return;
                        }
                        // 缺少权限时, 进入权限配置页面
                        if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                            getPermission();
                        } else {
                            showSelectHeadPicDialog();
                        }
                    } else if (!TextUtils.isEmpty(list.get(position).uri)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", list.get(position).uri);
                        bundle.putInt("type", 1);
                        AppointNursePayActivity.this.startActivity(BigImageActivity.class, bundle);
                    } else if (!TextUtils.isEmpty(list.get(position).url)) {
                        Bundle bundle = new Bundle();
                        bundle.putString("url", list.get(position).url);
                        bundle.putInt("type", 2);
                        AppointNursePayActivity.this.startActivity(BigImageActivity.class, bundle);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
//            if (type == 1 || type == 0) {
//                return list.size() + 1;
//            }
            return list.size();
        }


        class Holder extends RecyclerView.ViewHolder {

            ImageView image;
            ImageView btn_del_photo;

            public Holder(View itemView) {
                super(itemView);
                image = itemView.findViewById(R.id.image);
                btn_del_photo = itemView.findViewById(R.id.btn_del_photo);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }

        //data的返回值根据
        switch (requestCode) {
            case REQUEST_OPEN_CAMERA:
                //拍照返回
                getPresignedUrl(imgPathOri);
                break;
            case REQUEST_GALLERY:
                if (data != null) {
                    Uri imgUriSel = data.getData();
                    String imgPathSel = UriUtils.formatUri(this, imgUriSel);
                    getPresignedUrl(imgPathSel);
                }
                break;
            case 1:
                myFamily = (MyFamilyListResponse) data.getSerializableExtra(UIConstants.OBJ_MyFamilyListResponse);
                tv_patient_name.setText(myFamily.name);
                BaseApplication.currentFamilyId = myFamily.patientId;
                break;
            default:
                break;
        }
    }


    /**
     * 获取minio服务器域名
     *
     * @time 2020/12/2 10:21
     */
    private void getPresignedUrl(String imgPath) {
        showLoadingDialog(this);

        // 1-病历 2-评论(反馈) 3-头像 4-轮播图 5-用户资源 6-图标 7-封面',
        RestProxy.getInstance().getPresignedUrl("1", new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(String baseStringResponse) {
                try {
                    String data = baseStringResponse;
                    if (data.contains("?")) {
                        String substring = data.substring(0, data.indexOf("?"));
                        uploadFileMinio(imgPath,substring.substring(substring.lastIndexOf("/") + 1),baseStringResponse);
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传图片到minio服务器
     * <p>
     * * @time 2020/12/3 15:36
     */

    private void uploadFileMinio(String imgPath,String id,String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Log.e("TAG-路径-----", imgPath);
                    File file = new File(imgPath);
                    FileInputStream fileInputStream = new FileInputStream(file);
                    int available = fileInputStream.available(); //返回与之关联的文件的字节数
                    Log.e("字节数---", available + "");
                    OkHttpClient httpClient = new OkHttpClient();
                    MediaType mediaType = MediaType.parse("image/png");//设置类型
                    RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
                    Request request = new Request.Builder()
                            .url(url)
                            .put(requestBody)
                            .build(); //创建OkHttpClient对象
                    Call call = httpClient.newCall(request);
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(@NotNull Call call, @NotNull IOException e) {
                            Log.e("TAG-失败：", e.toString() + "");
                            dismissLoadingDialog();
                        }

                        @Override
                        public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                            assert response.body() != null;
                            String string = response.body().toString();
                            Log.e("minio成功---", string + "");
                            uploadFileTb(imgPath, available + "",id);
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }

    /**
     * 上传照片给医生查看
     *
     * @time 2020/12/2 9:55
     */
    private void uploadFileTb(String imgPathSel, String available, String id) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        // type:   15-病历 2-评论(反馈) 30-头像 92-聊天图片 ',
        RestProxy.getInstance().uploadFileTb("1", "15", id, BaseApplication.currentUserId, available, "0", new BaseObserver<PicUploadResponse>() {
            @Override
            public void onSuccess(PicUploadResponse picUploadResponse) {
                try {
                    runOnUiThread(() -> {
                        Photo photo = new Photo();
                        photo.uri = TextUtils.isEmpty(imgPathSel)?"":imgPathSel;
                        photo.resourceId = picUploadResponse.getResourceId();
                        //todo wjf
                        if (resourceId.length() == 0){
                            resourceId.append(picUploadResponse.getResourceId());

                        }else {
                            resourceId.append(",").append(picUploadResponse.getResourceId());

                        }
                        list.add(photo);
                        adapter.notifyDataSetChanged();
                        dismissLoadingDialog();
                    });

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissLoadingDialog();
                ToastUtil.onError(mContext, e);
            }

        });
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
            dialog = null;
        }
        if (mDateTimeDialogFragment != null && mDateTimeDialogFragment.isShowing()) {
            mDateTimeDialogFragment.dismiss();
            mDateTimeDialogFragment = null;
        }
        if (mPayDialog != null && mPayDialog.isShowing()) {
            mPayDialog.dismiss();
            mPayDialog = null;
        }
        if (mRulesDialogFragment != null && mRulesDialogFragment.isShowing()) {
            mRulesDialogFragment.dismiss();
            mRulesDialogFragment = null;
        }
        if (mSchudeleDialogFragment != null && mSchudeleDialogFragment.isShowing()) {
            mSchudeleDialogFragment.dismiss();
            mSchudeleDialogFragment = null;
        }
        if (mSelectPicModeDialog != null && mSelectPicModeDialog.isShowing()) {
            mSelectPicModeDialog.dismiss();
            mSelectPicModeDialog = null;
        }


    }

    /**
     * 拍照还是手机相册弹窗
     *
     * @time 2020/12/2 9:53
     */
    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        imgUriOri = FileProvider.getUriForFile(mContext, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }


    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    protected File createOriImageFile() throws IOException {
        String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    @SuppressLint("CheckResult")
    private void getPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("3", true);//申请退药
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(AppointNursePayActivity.this);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                //已经打开权限
                                showSelectHeadPicDialog();
                            } else {
                                ToastUtil.showToast(mContext, "请同意相册和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }


    private void showRulesDialogFragment() {
        mRulesDialogFragment = RulesDialogFragment.newInstance("1");
        mRulesDialogFragment.setmListener(() -> mRulesDialogFragment.dismiss());
        mRulesDialogFragment.show(getSupportFragmentManager(), "mSchudeleDialogFragment");
    }


}
